#include "stdafx.h"

#include "BankData.h"

#include "PC2Node.h"

#include "Client.h"



namespace PC2
{


Client::Client( ApplicationSettings* apSettings )
	: m_OwnNode(apSettings->m_NodeInfo)
	, m_ManagerNode(apSettings->m_RemoteNodeInfo)
{

}


Client::~Client()
{

}


void Client::Run()
{
	
	PC2Node lNode(m_OwnNode);
	printf("connecting to server\n");
	Trans lSendTrans;
	Trans lReceivedTrans;
	std::string lData;
	lSendTrans.m_Size = sizeof(Trans);
	lSendTrans.m_Type = EnumEcho;
	while (true)
	{
		lNode.SendTrans(&m_ManagerNode, &lSendTrans);
		bool lOK = lNode.WaitForData(&lReceivedTrans, &lData, _TIMEOUT_MS);
		if(lOK && lReceivedTrans.m_Type == EnumEcho)
			break;
	}
	printf("connect ok\n");

	BankTransaction lBankTrans;

	while (true)
	{
		printf("enter new trans [name] [from] [to] [value]:\n");
		scanf("%s %s %s %u", lBankTrans.m_Name, lBankTrans.m_BankFrom, lBankTrans.m_BankTo, &lBankTrans.m_Value);

		char lBuffer[256];
		Trans* lpResendTrans = (Trans*)lBuffer;
		lpResendTrans->m_Type = EnumPrepareRequest;
		lpResendTrans->AppendData((char*)&lBankTrans, sizeof(BankTransaction));

		lNode.SendTrans(&m_ManagerNode, lpResendTrans);

		while (true)
		{
			bool lOK = lNode.WaitForData(&lReceivedTrans, &lData, _TIMEOUT_MS);
			if(lOK 
				&& ( lReceivedTrans.m_Type == EnumAbortRequest || lReceivedTrans.m_Type == EnumCommitRequest) )
				break;
		}

		if(lReceivedTrans.m_Type == EnumCommitRequest)
		{
			printf("OK\n");
		}
		else
		{
			printf("Failed\n");
		}
	}

}


}